package org.summerframework.component.note.code.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.summerframework.component.mybatisplus.AbstractBasePlusService;
import org.summerframework.component.note.code.model.dao.NoteCodeRecordDAO;
import org.summerframework.component.note.code.model.domain.NoteCodeRecordDO;
import org.summerframework.component.note.code.service.NoteCodeRecordService;
import org.summerframework.component.note.code.service.dto.NoteCodeRecordDTO;
import org.summerframework.component.note.code.service.dto.NoteCodeRecordQueryDTO;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service("noteCodeRecordService")
public class NoteCodeRecordServiceImpl extends AbstractBasePlusService<NoteCodeRecordDAO, NoteCodeRecordDTO, NoteCodeRecordQueryDTO, NoteCodeRecordDO> implements NoteCodeRecordService {

    @Override
    public LambdaQueryWrapper<NoteCodeRecordDO> getWrapper(NoteCodeRecordQueryDTO query) {
        return Wrappers.<NoteCodeRecordDO>lambdaQuery()
                .orderBy(Objects.nonNull(query.getOrderByUpdateTime()), query.getOrderByUpdateTime() != null ? query.getOrderByUpdateTime() : false, NoteCodeRecordDO::getUpdateTime)
                .eq(StringUtils.isNotBlank(query.getCode()), NoteCodeRecordDO::getCode, query.getCode())
                .orderBy(Objects.nonNull(query.getOrderByCreateTime()), query.getOrderByCreateTime() != null ? query.getOrderByCreateTime() : false, NoteCodeRecordDO::getCreateTime)
                .eq(StringUtils.isNotBlank(query.getIp()), NoteCodeRecordDO::getIp, query.getIp())
                .orderBy(Objects.nonNull(query.getOrderById()), query.getOrderById() != null ? query.getOrderById() : false, NoteCodeRecordDO::getId)
                .eq(Objects.nonNull(query.getTemplateId()), NoteCodeRecordDO::getTemplateId, query.getTemplateId())
                .eq(StringUtils.isNotBlank(query.getAccount()), NoteCodeRecordDO::getAccount, query.getAccount())
                .eq(Objects.nonNull(query.getStatus()), NoteCodeRecordDO::getStatus, query.getStatus());
    }

    @Override
    public Integer selectCountTodayByIp(String ip) {
        return baseDAO.selectCountTodayByIp(ip);
    }

    @Override
    public Integer[] selectCountByAccount(String account) {
        return baseDAO.selectCountByAccount(account);
    }

    @Override
    public NoteCodeRecordDTO selectByLastAccount(String account, Long templateId) {
        return selectOne(NoteCodeRecordQueryDTO.builder().account(account).templateId(templateId).build());
    }

    @Override
    public NoteCodeRecordDTO selectByLastAccount(String account, Long templateId, String code) {
        return selectOne(NoteCodeRecordQueryDTO.builder().account(account).templateId(templateId).code(code).orderByCreateTime(false).build());
    }
}
